package com.beaven.imserver.net.utils;

import com.beaven.imserver.net.bean.api.base.PushModel;
import com.beaven.imserver.net.bean.db.User;
import com.gexin.rp.sdk.base.IBatch;
import com.gexin.rp.sdk.base.IPushResult;
import com.gexin.rp.sdk.base.impl.SingleMessage;
import com.gexin.rp.sdk.base.impl.Target;
import com.gexin.rp.sdk.http.IGtPush;
import com.gexin.rp.sdk.template.TransmissionTemplate;
import com.google.common.base.Strings;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * author: Beaven
 * time: 2017/5/31 18:00
 */
public class PushUtil {

  private static final String appId = "EXl89x0nh97t0k6U4cnYA2";
  private static final String appKey = "gAKunf2byy87hiezKFM4g3";
  private static final String masterSecret = "mWhhIUYvIn83sa0Khdtb69";
  private static final String host = "http://sdk.open.api.igexin.com/apiex.htm";

  // 给每个人发送消息的一个Bean封装
  private static class BatchBean {
    SingleMessage message;
    Target target;

    BatchBean(SingleMessage message, Target target) {
      this.message = message;
      this.target = target;
    }
  }

  private IGtPush pusher;

  private List<BatchBean> beans = new ArrayList<>();

  public PushUtil() {
    this.pusher = new IGtPush(host, appKey, masterSecret);
  }

  public boolean addMessage(User receiver, PushModel model) {
    if (receiver == null || model == null ||
        Strings.isNullOrEmpty(receiver.getPushId())) {
      return false;
    }
    String pushString = model.getPushString();
    if (Strings.isNullOrEmpty(pushString)) {
      return false;
    }

    BatchBean batchBean = build(receiver.getPushId(), pushString);
    beans.add(batchBean);
    return true;
  }

  public boolean send() {
    IBatch iBatch = pusher.getBatch();

    boolean hasMessage = false;

    try {
      for (BatchBean bean : beans) {
        iBatch.add(bean.message, bean.target);
        hasMessage = true;
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    // 没有数据就直接返回
    if (!hasMessage) {
      return false;
    }
    IPushResult result = null;
    try {
      result = iBatch.submit();
    } catch (IOException e) {
      e.printStackTrace();
      // 失败情况下再次发送
      try {
        iBatch.retry();
      } catch (IOException e1) {
        e1.printStackTrace();
      }
    }

    try {
      if (result != null) {
        Logger.getLogger("PushDispatcher")
            .log(Level.INFO, (String) result.getResponse().get("result"));
        return true;
      } else {
        Logger.getLogger("PushDispatcher")
            .log(Level.WARNING, "推送服务器响应异常！！！");
        return false;
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return false;
  }

  private BatchBean build(String pushId, String pushString) {
    TransmissionTemplate template = new TransmissionTemplate();
    template.setAppId(appId);
    template.setAppkey(appKey);
    template.setTransmissionContent(pushString);
    template.setTransmissionType(0);

    SingleMessage message = new SingleMessage();
    message.setData(template); // 把透传消息设置到单消息模版中
    message.setOffline(true); // 是否运行离线发送
    message.setOfflineExpireTime(24 * 3600 * 1000); // 离线消息时常

    Target target = new Target();
    target.setAppId(appId);
    target.setClientId(pushId);

    return new BatchBean(message, target);
  }
}
